package com.acoreful.sample.commons.web.utils;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.acoreful.sample.commons.utils.TokenUtils;

public class ServletUtils {
	public static void validate(HttpServletRequest req,HttpServletResponse res){
		//判断Token是否合法，合法执行，并更新Token
	      Cookie cookies[] = req.getCookies();
	      String token = "";
	      String tokenNext = "";
	      String password = "";
	     
	      for (Cookie c : cookies) {
	          if (c.getName().equals("token")) {
	              token = c.getValue();
	          } else if (c.getName().equals("next")) {
	              tokenNext = c.getValue();
	          } else if (c.getName().equals("password")) {
	              password = c.getValue();
	          } else if(c.getName().equals("userName")){
	             req.setAttribute("userName", c.getValue());
	               
	          } 
	      }
	      if (!TokenUtils.validToken(token, password) && !TokenUtils.validToken(tokenNext, password)) {
	          //此处处理的未登录信息
	          return;
	      }
	 
	      Date now = new Date(System.currentTimeMillis());
	      token = TokenUtils.getToken(password, now);
	      tokenNext = TokenUtils.getToken(password, TokenUtils.getNextHour(now));
	      Cookie tokenCookie = new Cookie("token", token);
	      tokenCookie.setPath("/");
	      Cookie nextTokenCookie = new Cookie("next", tokenNext);
	      nextTokenCookie.setPath("/");
	     //将两个新token发给客户端
	      res.addCookie(tokenCookie);
	      res.addCookie(nextTokenCookie);
	}
	
	/**
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request){
		return request.getHeader("X-Requested-With") != null;
	}
}
